import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/playbill/central_stage/home_production.dart';
import 'package:thal/playbill/community_forum/community_production.dart';
import 'package:thal/playbill/messenger/chat_production.dart';
import 'package:thal/playbill/profile_saga/profile_production.dart';

part 'main_production.page.dart';

/// 主页面
@PagePath('/main')
class MainProduction extends StatefulWidget {
  const MainProduction({super.key});

  @pageRouteQuery
  static const query = _$MainProductionQuery();

  @override
  State<MainProduction> createState() => _MainProductionState();
}

class _MainProductionState extends State<MainProduction>
    with TickerProviderStateMixin {
  int _currentIndex = 0;
  late PageController _pageController;
  late List<AnimationController> _animationControllers;
  late List<Animation<double>> _scaleAnimations;

  // 四个页面的路由
  final List<Widget> _pages = [
    const HomeProduction(),
    const CommunityProduction(),
    const ChatProduction(),
    const ProfileProduction(),
  ];

  // 底部导航栏图标配置
  final List<Map<String, String>> _navigationItems = [
    {
      'selected': AssetManifest.homeSelect,
      'unselected': AssetManifest.homeUnselect,
      'label': 'Home',
    },
    {
      'selected': AssetManifest.communitySelect,
      'unselected': AssetManifest.communityUnselect,
      'label': 'Community',
    },
    {
      'selected': AssetManifest.messageSelect,
      'unselected': AssetManifest.messageUnselect,
      'label': 'Message',
    },
    {
      'selected': AssetManifest.profileSelect,
      'unselected': AssetManifest.profileUnselect,
      'label': 'Profile',
    },
  ];

  @override
  void initState() {
    super.initState();
    _pageController = PageController();

    // 初始化动画控制器
    _animationControllers = List.generate(
      4,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 200),
        vsync: this,
      ),
    );

    // 初始化缩放动画
    _scaleAnimations =
        _animationControllers
            .map(
              (controller) => Tween<double>(begin: 1.0, end: 0.8).animate(
                CurvedAnimation(parent: controller, curve: Curves.easeInOut),
              ),
            )
            .toList();
  }

  @override
  void dispose() {
    _pageController.dispose();
    for (var controller in _animationControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  /// 切换页面
  void _switchPage(int index) {
    if (_currentIndex != index) {
      setState(() {
        _currentIndex = index;
      });
      _pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  /// 处理底部导航栏点击
  void _handleNavigationTap(int index) {
    for (int i = 0; i < _animationControllers.length; i++) {
      if (i == index) {
        _animationControllers[i].forward().then((_) {
          _animationControllers[i].reverse();
        });
      } else {
        if (_animationControllers[i].isAnimating) {
          _animationControllers[i].stop();
        }
        _animationControllers[i].reset();
      }
    }

    // 切换页面
    _switchPage(index);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 页面内容
          PageView(
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
            children: _pages,
          ),

          // 底部导航栏
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: _buildBottomNavigationBar(),
          ),
        ],
      ),
    );
  }

  /// 构建底部导航栏
  Widget _buildBottomNavigationBar() {
    return AspectRatio(
      aspectRatio: 390 / 105,
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.navigationBackground),
            fit: BoxFit.fill,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: List.generate(
            _navigationItems.length,
            (index) => _buildNavigationItem(index),
          ),
        ).wrapHorizontal(20.w).wrapVertical(16.h),
      ),
    );
  }

  /// 构建单个导航项
  Widget _buildNavigationItem(int index) {
    final isSelected = _currentIndex == index;
    final item = _navigationItems[index];

    return AnimatedBuilder(
      animation: _scaleAnimations[index],
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimations[index].value,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 22.w,
                height: 22.w,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(
                      isSelected ? item['selected']! : item['unselected']!,
                    ),
                    fit: BoxFit.contain,
                  ),
                ),
              ),

              8.h.heightBox,

              // 标签
              Text(item['label']!)
                  .fontSize(12.sp)
                  .textColor(
                    isSelected ? ColorPalette.black : ColorPalette.iconGrey,
                  )
                  .arimo(weight: FontWeight.w700),
            ],
          ),
        );
      },
    ).withTapEffect(
      onTap: () => _handleNavigationTap(index),
      scaleFactor: 0.95,
    );
  }
}
